#!/usr/bin/env python
# -*- coding: utf-8 -*-

import os


def read_file(filename):
    if os.path.exists(filename):
        with open(filename) as f:
            return f.read()
    else:
        return '0'


def to_bytes(s):
    s = s.strip('Bb \n')
    unit = s[-1]
    if unit in ('K', 'k'):
        return int(float(s[:-1]) * (2 ** 10))
    elif unit in ('M', 'm'):
        return int(float(s[:-1]) * (2 ** 20))
    elif unit in ('G', 'g'):
        return int(float(s[:-1]) * (2 ** 30))
    elif unit in ('T', 't'):
        return int(float(s[:-1]) * (2 ** 40))
    else:
        return int(float(s))


class Bcache(object):
    def __init__(self):
        pass

    @staticmethod
    def dirty_data(dev):
        s = read_file('/sys/block/%s/bcache/dirty_data' % dev)
        return to_bytes(s)

    @staticmethod
    def disk_stat(total, dirty_data):
        total = to_bytes(total) / 1024 / 1024
        dirty_data = dirty_data / 1024 / 1024
        return {
            'disk': '0',
            'online': '1',
            'total': str(total),
            'used': str(dirty_data),
            'cache': '0',
            'cached': '0',
            'wbcount': '0',
            'wbtotal': '0',
            'wbused': '0',
        }


if __name__ == '__main__':
    total = '893.8GB'
    dirty_data = Bcache.dirty_data('sdf')
    print dirty_data
    print Bcache.disk_stat(total, dirty_data)
